package user

import (
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/controller"
	user2 "git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto/user"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/base/user"
	userService "git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/base/user/user_service"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"strconv"
)

type SyncUserController struct {
	controller.BaseController
	userService    userService.UserSerivceIface
	userNewService user.UserNewServiceIface
}

// NewSyncUserController
// 构造函数
func NewSyncUserController(userService userService.UserSerivceIface, userNewService user.UserNewServiceIface) *SyncUserController {
	return &SyncUserController{userService: userService, userNewService: userNewService}
}

// RegisterRouter
// 注册路由
func (c *SyncUserController) RegisterRouter(g *gin.RouterGroup) {
	//  全量同步用户信息
	//g.GET("/all-user", c.SyncAllUser)
	// 增量同步用户信息
	//g.POST("/incr-user", c.IncrSyncUser)

	// 全量同步角色信息
	//g.GET("/all-role", c.SyncAllRole)

	// 全量同步用户权限信息
	//g.GET("/all-user-action-right-infos", c.SyncAllUserActionRightInfos)

	// 全量同步组织信息
	//g.GET("/all-organizations", c.SyncAllOrganizations)

	// 全量同步用户角色关系信息
	//g.GET("/all-user-role-relation", c.SyncAllUserRoleRelation)

	// 同步租户权益
	//g.POST("/all-tenant-profit", c.SyncAllTenantProfit)

	// 同步权限数据
	//g.POST("/organization", c.syncOrganization)
}

func (c *SyncUserController) SyncAllTenantProfit(ctx *gin.Context) {
	response := map[string]interface{}{}
	req := &user2.SyncAllTenantProfitRequest{}
	if err := ctx.ShouldBind(req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	stark.Logger.Info(ctx, "租户权益同步请求数据:%+v", req)
	tenantCode := req.TenantCode

	if tenantCode == "" {
		stark.Logger.Error(ctx, "权益同步租户code为空")
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "权益同步租户code为空")
		return
	}
	_, err := c.userService.SyncAllTenantProfit(ctx, tenantCode, req)
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncAllTenantProfit-error: %+v, tenant_code: %s", err.Error(), tenantCode)
		c.Fail(ctx, ykerrcode.FAIL, err.Error())
		return
	}
	c.Success(ctx, response)
}

// SyncAllOrganizations 全量同步组织信息
func (c *SyncUserController) SyncAllOrganizations(ctx *gin.Context) {
	response := map[string]interface{}{}

	tenantCode := ctx.Query("tenant_code")
	if tenantCode == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "租户编号为空")
		return
	}

	flag, err := c.userService.SyncAllOrganizations(ctx, tenantCode)
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncAllOrganizations-error: %+v, tenant_code: %s", err.Error(), tenantCode)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}
	if flag == false {
		stark.Logger.Errorf(ctx, "SyncAllOrganizations-同步失败, tenant_code: %s", tenantCode)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "同步组织信息失败")
		return
	}

	c.Success(ctx, response)
}

// SyncAllUserRoleRelation 全量同步用户角色关联信息
func (c *SyncUserController) SyncAllUserRoleRelation(ctx *gin.Context) {
	response := map[string]interface{}{}

	tenantCode := ctx.Query("tenant_code")
	if tenantCode == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "租户编号为空")
		return
	}
	pagesizeParams := ctx.DefaultQuery("pagesize", "10")
	pagesize, _ := strconv.ParseInt(pagesizeParams, 10, 32)
	if pagesize < 0 || pagesize > 100 {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "分页size必须大于0，小于等于100")
		return
	}

	flag, err := c.userService.SyncAllUserRoleRelation(ctx, tenantCode, int32(pagesize))
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncAllUserRoleRelation-error: %+v, tenant_code: %s, pagesize:%s", err.Error(), tenantCode, pagesize)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}
	if flag == false {
		stark.Logger.Errorf(ctx, "SyncAllUserRoleRelation同步失败, tenant_code: %s, pagesize:%s", tenantCode, pagesize)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "用户角色关系同步失败")
		return
	}

	c.Success(ctx, response)
}

// SyncAllUserActionRightInfos 全量同步用户权限信息
func (c *SyncUserController) SyncAllUserActionRightInfos(ctx *gin.Context) {
	response := map[string]interface{}{}

	tenantCode := ctx.Query("tenant_code")
	if tenantCode == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "租户编号为空")
		return
	}

	flag, err := c.userService.SyncAllUserActionRightInfos(ctx, tenantCode)
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncAllUserActionRightInfos-error: %+v, tenant_code: %s", err.Error(), tenantCode)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}
	if flag == false {
		stark.Logger.Errorf(ctx, "SyncAllUserActionRightInfos-同步失败, tenant_code: %s", tenantCode)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "同步用户权限失败")
		return
	}

	c.Success(ctx, response)
}

// SyncAllRole 全量同步角色信息
func (c *SyncUserController) SyncAllRole(ctx *gin.Context) {
	//time.Sleep(time.Second * 120)
	response := map[string]interface{}{}

	tenantCode := ctx.Query("tenant_code")
	if tenantCode == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "租户编号为空")
		return
	}
	pagesizeParams := ctx.DefaultQuery("pagesize", "10")
	if pagesizeParams == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "分页size必须大于0，小于等于10")
		return
	}
	pagesize, err := strconv.ParseInt(pagesizeParams, 10, 32)
	if pagesize < 0 || pagesize > 10 {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "分页size必须大于0，小于等于10")
		return
	}

	flag, err := c.userService.SyncAllRole(ctx, tenantCode, int32(pagesize))
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncAllRole-error: %+v, tenant_code: %s, pagesize:%s", err.Error(), tenantCode, pagesize)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}
	if flag == false {
		stark.Logger.Errorf(ctx, "SyncAllRole同步失败, tenant_code: %s, pagesize:%s", tenantCode, pagesize)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "用户角色失败")
		return
	}

	c.Success(ctx, response)
}

// SyncAllUser 全量同步用户信息
func (c *SyncUserController) SyncAllUser(ctx *gin.Context) {
	response := map[string]interface{}{}

	tenantCode := ctx.Query("tenant_code")
	if tenantCode == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "租户编号为空")
		return
	}
	pagesizeParams := ctx.DefaultQuery("pagesize", "10")
	if pagesizeParams == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "分页size必须大于0，小于等于10")
		return
	}
	pagesize, err := strconv.ParseInt(pagesizeParams, 10, 32)
	if pagesize < 0 || pagesize > 10 {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "分页size必须大于0，小于等于10")
		return
	}

	flag, err := c.userService.SyncAllUser(ctx, tenantCode, int32(pagesize))
	if err != nil {
		stark.Logger.Errorf(ctx, "SyncAllUser-error: %+v, tenant_code: %s, pagesize:%s", err.Error(), tenantCode, pagesize)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}
	if flag == false {
		stark.Logger.Errorf(ctx, "SyncAllUser同步失败, tenant_code: %s, pagesize:%s", tenantCode, pagesize)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "用户同步失败")
		return
	}

	c.Success(ctx, response)
}

type IncrData struct {
	Data struct {
		Operation string `json:"Operation"`
		UserList  []struct {
			UserId             int64  `json:"user_id"`
			UserGuid           string `json:"UserGuid"`
			MobilePhone        string `json:"MobilePhone"`
			UserName           string `json:"UserName"`
			UserCode           string `json:"UserCode"`
			IsDisable          int32  `json:"IsDisabeld"`
			Password           string `json:"Password"`
			BuGuid             string `json:"BusinessUnitId"`
			Email              string `json:"Email"`
			Position           string `json:"Position"`
			Salt               string `json:"Salt"`
			PasswordModifyTime string `json:"PasswordModifyTime"`
			CreatedTime        string `json:"CreatedTime"`
			ModifiedTime       string `json:"ModifiedTime"`
		} `json:"Users"`
	} `json:"Data"`
	TenantInfo struct {
		TenantCode string `json:"TenantCode" form:"TenantCode" bidding:"required,max=255"`
	} `json:"TenantInfo"`
}

// IncrSyncUser 增量同步用户信息
func (c *SyncUserController) IncrSyncUser(ctx *gin.Context) {
	response := map[string]interface{}{}
	req := &IncrData{}
	if err := ctx.ShouldBind(req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	stark.Logger.Info(ctx, "增量同步请求数据:%+v", req)
	tenantCode := req.TenantInfo.TenantCode
	if tenantCode == "" {
		stark.Logger.Error(ctx, "增量同步租户code为空")
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "增量同步租户code为空")
		return
	}
	operation := req.Data.Operation
	if operation == "" {
		stark.Logger.Error(ctx, "增量同步操作类型为空")
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "增量同步操作类型为空")
		return
	}
	if operation != "I" && operation != "U" && operation != "D" {
		stark.Logger.Error(ctx, "增量同步操作类型错误")
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "增量同步操作类型错误")
		return
	}
	if len(req.Data.UserList) > 0 {
		var userList []userService.IncrUserInfo
		for _, info := range req.Data.UserList {
			isDisable := false
			if info.IsDisable != 0 {
				isDisable = true
			}
			userInfo := userService.IncrUserInfo{
				UserId:             info.UserId,
				UserGuid:           info.UserGuid,
				MobilePhone:        info.MobilePhone,
				UserName:           info.UserName,
				UserCode:           info.UserCode,
				IsDisable:          isDisable,
				Password:           info.Password,
				Salt:               info.Salt,
				BuGuid:             info.BuGuid,
				Email:              info.Email,
				Position:           info.Position,
				PasswordModifyTime: info.PasswordModifyTime,
				CreatedTime:        info.CreatedTime,
				ModifiedTime:       info.ModifiedTime,
			}
			userList = append(userList, userInfo)
		}
		_, err := c.userService.IncrSyncUser(ctx, tenantCode, operation, userList)
		if err != nil {
			stark.Logger.Errorf(ctx, "增量同步数据报错，IncrSyncUser tenantCode:%s,operation:%s, userList:%+v", tenantCode, operation, userList)
		}
		ctx.Set(authorize.TENANT_CODE_KEY, tenantCode)
		_, err = c.userNewService.SyncUserByJm(ctx, operation, userList)
		if err != nil {
			stark.Logger.Errorf(ctx, "增量同步数据报错，SyncUserByJm tenantCode:%s,operation:%s, userList:%+v, err:%+v", tenantCode, operation, userList, err)
		}
	} else {
		stark.Logger.Warn(ctx, "增量同步数据为空,租户code：%s", tenantCode)
	}
	c.Success(ctx, response)
}

func (c *SyncUserController) syncOrganization(ctx *gin.Context) {
	stark.Logger.Infof(ctx, "syncOrganization", ctx.Request.Body)
	c.Success(ctx, nil)
}
